<?php
declare(strict_types=1);
namespace app\admin\service\sys;

use app\admin\model\AdminRule;

/**
 *后台菜单/权限 逻辑处理 服务类
 * 列表 添加 编辑 状态改变等
 **/
class RuleService
{
    /**
     * 权限菜单列表
    */
    public static function ruleMenuList(){
        $ss = AdminRule::where([['pid','>',0]])->order('sort','ASC')->order('id','ASC')->column('id,title,path,type,state,pid,icon,sort');
        return $ss;
    }
    /**
     * 添加 后台菜单/权限
     */
    public static function addRuleMenu($params)
    {
        $name = '';
        if(!empty($params['path'])) {
            $name = str_replace('/', '_', $params['path']); //生成别名name;
        }
        //id 大于0 时为编辑
        if (isset($params['id']) && $params['id'] > 0) {
            //编辑
            $params['state'] = $params['state'] ? 1 : 0;
            $model = AdminRule::field('id,title,path,type,state,pid,icon,sort')->find($params['id']);
            if ($model) {
                if(empty($model->name) && !empty($name)){
                    $params['name'] = $name;
                }
                $model->save($params);
                return $model;
            }
            return false;
        }
        //添加
        unset($params['id']);
        $params['state']=1;
        $params['name'] = $name;
        $model = new AdminRule();
        $model->save($params);
        return $model;
    }

    /**
     * 二级菜单 列表
     * 用于联级显示
     * 用于菜单添加选择
    */
    public static function getRuleArr(){

        $list = AdminRule::where('pid',0)->where('state',1)->order('sort','ASC')->column('id,title');
        if(!empty($list)){
            foreach ($list as $key=>$vs){
                $list[$key]['children'] = AdminRule::where('pid',$vs['id'])->order('sort','ASC')->order('id','DESC')->column('id,title');
            }
        }

        return $list;
    }

    /**
     *  全部菜单 递归分类
     * 使用于 角色权限选择
     * 无限级
     */
    public static function getRoleRuleArr(){

        $list = AdminRule::where('pid',0)->where('state',1)->order('sort','ASC')->column('id,title,pid');

        return $list;
    }
}

